import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Button, Input, Upload, Divider, message } from "antd";
import { PlusOutlined, LoadingOutlined } from "@ant-design/icons";
import type { UploadChangeParam } from "antd/es/upload";
import type { UploadFile, UploadProps } from "antd/es/upload/interface";
import { cleanPermissions, cleanToken, cleanUserInfo } from "@/stores/actions";
import { $get, $post } from "@/api/RestUtils";
import { encrypt } from "@/utils/RSAUtils";
import PubSub from "pubsub-js";
import { useDispatch, useSelector } from "react-redux";
import "./index.less";

const App: React.FC = () => {
  const [infoForm] = Form.useForm();
  const [passForm] = Form.useForm();

  const [avatarPath, setAvatarPath] = useState<string>();
  const [loading, setLoading] = useState(false);

  const token = useSelector((state: any) => state.token);

  const navigate = useNavigate();
  const dispatch = useDispatch();

  useEffect(() => {
    getUserInfo();
  }, []);

  const getUserInfo = () => {
    $get("/user/info", null)
      .then((res: any) => {
        if (res.code === 0) {
          let info = res.data;
          infoForm.setFieldValue("username", info.username);
          infoForm.setFieldValue("nickName", info.nickName);
          infoForm.setFieldValue("mail", info.mail);
          infoForm.setFieldValue("phone", info.phone);
          setAvatarPath(info.avatarPath);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const saveInfo = (formData: any) => {
    formData.avatarPath = avatarPath;
    $post("/user/updateSelf", formData)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
          PubSub.publish("userInfoChange", true);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const checkRepeatPass = (_: any, value: string) => {
    if (value != passForm.getFieldValue("newPass")) {
      return Promise.reject(new Error("两次输入密码不一致"));
    } else {
      return Promise.resolve();
    }
  };

  const changePass = (formData: any) => {
    formData.oldPass = encrypt(formData.oldPass);
    formData.newPass = encrypt(formData.newPass);
    formData.checkPass = encrypt(formData.checkPass);
    $post("/user/changePass", formData)
      .then((res: any) => {
        if (res.code === 0) {
          dispatch(cleanToken())
          dispatch(cleanUserInfo())
          dispatch(cleanPermissions())
          message.success(res.msg);
          navigate("/login");
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const avatarChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      setLoading(false);
      let res = info.file.response;
      if (res.code === 0) {
        let avatar = res.data;
        setAvatarPath(avatar);
      } else {
        message.error(res.msg);
      }
    }
  };

  const checkFile = (file: File) => {
    if (file.size > 512 * 1024) {
      message.error("图片大小超过512KB");
      return Upload.LIST_IGNORE;
    } else {
      return true;
    }
  };

  const resetPassForm = () => {
    passForm.resetFields();
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  return (
    <>
      <div className="person-info">
        <div className="infomation">
          <div className="title">修改个人信息</div>
          <div className="form-body">
            <Form
              form={infoForm}
              labelAlign="right"
              layout="horizontal"
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 14 }}
              colon={false}
              onFinish={saveInfo}
            >
              <div className="form-avatar">
                <Upload
                  name="file"
                  headers={{
                    satoken: "Bearer " + token,
                  }}
                  accept=".jpg, .png, .jpeg"
                  listType="picture-circle"
                  className="avatar-uploader"
                  showUploadList={false}
                  action={import.meta.env.VITE_BASE_URL + "/file/upload"}
                  beforeUpload={checkFile}
                  onChange={avatarChange}
                >
                  {avatarPath ? (
                    <img
                      src={import.meta.env.VITE_REMOTE_FILE_URL + avatarPath}
                      alt="加载失败"
                      style={{
                        width: "100%",
                        height: "100%",
                        objectFit: "cover",
                        borderRadius: "50%",
                      }}
                    />
                  ) : (
                    uploadButton
                  )}
                </Upload>
              </div>
              <Form.Item name="nickName" label="用户名称">
                <Input disabled />
              </Form.Item>
              <Form.Item name="username" label="用户账号">
                <Input disabled />
              </Form.Item>
              <Form.Item
                name="mail"
                label="邮箱"
                rules={[{ max: 32, min: 8, message: "长度在8~32位之间" }]}
              >
                <Input placeholder="邮箱" maxLength={32} />
              </Form.Item>
              <Form.Item
                name="phone"
                label="手机号码"
                required
                rules={[
                  { required: true, type: "string", message: "请输入用户账号" },
                  { max: 14, min: 7, message: "长度在7~14位之间" },
                ]}
              >
                <Input placeholder="手机号码" maxLength={14} />
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
        <div className="pass">
          <div className="title">修改密码</div>
          <Divider />
          <div className="form-body">
            <Form
              form={passForm}
              labelAlign="right"
              layout="horizontal"
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 16 }}
              colon={false}
              onFinish={changePass}
            >
              <Form.Item
                name="oldPass"
                label="原密码"
                validateFirst
                rules={[
                  { required: true, type: "string", message: "请输入原密码" },
                  { max: 16, min: 8, message: "密码长度在8~16位" },
                ]}
              >
                <Input type="password" placeholder="原密码" />
              </Form.Item>
              <Form.Item
                name="newPass"
                label="新密码"
                validateFirst
                rules={[
                  { required: true, type: "string", message: "请输入新密码" },
                  { max: 16, min: 8, message: "密码长度在8~16位" },
                ]}
              >
                <Input type="password" placeholder="新密码" />
              </Form.Item>
              <Form.Item
                name="checkPass"
                label="重复新密码"
                validateFirst
                rules={[
                  {
                    required: true,
                    type: "string",
                    message: "请重复输入新密码",
                  },
                  { max: 16, min: 8, message: "密码长度在8~16位" },
                  { validator: checkRepeatPass },
                ]}
              >
                <Input type="password" placeholder="重复新密码" />
              </Form.Item>
              <Form.Item labelCol={{ span: 0 }} wrapperCol={{ span: 20 }}>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
                <Button onClick={resetPassForm}>重置</Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    </>
  );
};

export default App;
